package com.baizhi.controller;

import com.baizhi.entity.Article;
import com.baizhi.service.ArticleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @ResponseBody
    @RequestMapping("selectAllArticle")
    public Map selectAllArticle(String name ,Integer page,Integer limit){
        Map map = new HashMap();
        PageInfo<Article> pageInfo = articleService.selectAllArticle(name, page, limit);
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }
    @ResponseBody
    @RequestMapping("selectOneArticle")
    public Article selectOneArticle(Integer id){

        Article article = articleService.selectOneArticle(id);

        return article;
    }
    @ResponseBody
    @RequestMapping("insertArticle")
    public Map insertArticle(Article article){
        Map map = new HashMap();
        Boolean isAdd = articleService.insertArticle(article);
        map.put("isAdd",isAdd);
        return map;
    }
    @ResponseBody
    @RequestMapping("updateArticle")
    public Map updateArticle(Article article){
        Map map = new HashMap();
        Boolean isUpdate = articleService.updateArticle(article);
        map.put("isUpdate",isUpdate);
        return map;
    }
    @ResponseBody
    @RequestMapping("upload")
    public Map upload(MultipartFile file) throws IOException {
        //拼接uuid  防止文件名重复上传失败
        String imageName = UUID.randomUUID().toString()+file.getOriginalFilename();
        //指明上传位置
        file.transferTo(new File("d:\\photo",imageName));
        Map map = new HashMap();
        //将文件名存入map集合
        map.put("imageName",imageName);
        return map;
    }
    @ResponseBody
    @RequestMapping("deleteArticle")
    public Map deleteArticle(Article article){
        Map map = new HashMap();
        if(article.getStatus()==0){
            article.setStatus(1);
        }else{
            article.setStatus(0);
        }
        Boolean isDelete = articleService.updateArticle(article);
        map.put("isDelete",isDelete);
        return map;
    }

}
